/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package admin.hibernate.model.dao;

import hibernate.pojo.Sanpham;
import hibernate.util.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Administrator
 */
public class AdminSanPhamDAO 
{
    //<editor-fold defaultstate="collapsed" desc="1. Lấy sản phẩm by ID">
    public static Sanpham getProductByID(int maSanPham)
    {
        Sanpham sanPham = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try
        {
            sanPham = (Sanpham) session.get(Sanpham.class, maSanPham);
        }
        catch(HibernateException hex)
        {
            System.err.print(hex);
        }finally
        {
            session.close();
        }
        return sanPham;
    }
    //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="2. Cập nhật sản phẩm">
     public static boolean updateProduct(Sanpham product){
         Session session = HibernateUtil.getSessionFactory().openSession();
         Transaction tran = null;
         try{
             tran = session.beginTransaction();
             session.update(product);
             tran.commit();
         }catch(Exception hex){
             System.err.print(hex);
             tran.rollback();
             return false;
         }
         finally {
             session.close();
         }
         return true;
     }
     //</editor-fold>
     
     //<editor-fold defaultstate="collapsed" desc="3. Thêm sản phẩm">
     public static boolean addProduct(Sanpham product){
         Session session = HibernateUtil.getSessionFactory().openSession();
         Transaction tran = null;
         try{
             tran = session.beginTransaction();
             session.save(product);
             tran.commit();
         }catch(Exception hex){
             System.err.print(hex);
             tran.rollback();
             return false;
         }
         finally {
             session.close();
         }
         return true;
     }
     //</editor-fold>
     
     //<editor-fold defaultstate="collapsed" desc="4. Del Pro">
   
    //</editor-fold>
     
     //<editor-fold defaultstate="collapsed" desc="5. Get recently added">
     public static int getRecentlyAddedProduct(){
        int masp = 0;
        Session session = HibernateUtil.getSessionFactory().openSession();
        String hql = "select max(maSanPham) as masp from Sanpham";
        try{
            Query query = session.createQuery(hql);
            Object objMacthd = query.uniqueResult();
            masp = (Integer)objMacthd;
        }catch(HibernateException ex){
            ex.printStackTrace();
        }
        finally{
            session.close();
        }
        return masp;
    }
     
     //</editor-fold>
}
